package Engine.Movie
{
	import Engine.Movie.PngMovie;
	
	import Interface.Movie.IMovieBase;
	
	import flash.display.Sprite;
	import flash.events.Event;
	
	import library.Function.Dict;

	public class MovieBase extends Sprite implements IMovieBase
	{
		private var _actionDict:Dict = new Dict;
		private var _actionSpeed:int = 4;
		
		private var _movieSprite:Sprite;
		
		private var _currentFps:int = 0;
		private var _currentMoviePng:PngMovie = null;
		
		public function MovieBase()
		{
			super();
			this.addEventListener(Event.REMOVED_FROM_STAGE,onRemoveFromStage);
			this.addEventListener(Event.ADDED_TO_STAGE,onAddToStage);
			this._movieSprite = new Sprite();
			this.addChild(this._movieSprite);
		}
		
		private function onAddToStage(event:Event):void
		{
			this.startORstop(true);
		}
		
		private function onRemoveFromStage(event:Event):void
		{
			this.startORstop(false);
		}
		
		private function startORstop(isStart:Boolean):void
		{
			if(isStart)
			{
				this.addEventListener(Event.ENTER_FRAME,onEnterFrame);
			}
			else
			{
				this.removeEventListener(Event.ENTER_FRAME,onEnterFrame);
				if(this._currentMoviePng != null)
					this._currentMoviePng.stop();
			}
		}
		
		private function onEnterFrame(event:Event):void
		{
			if(this._currentFps < this._actionSpeed)
			{
				this._currentFps++;
				return;
			}
			this._currentFps = 0;
			this._movieSprite.graphics.clear();
			this._movieSprite.graphics.beginBitmapFill(this._currentMoviePng.nextFrame(),null,false,true);
			this._movieSprite.graphics.drawRect(0,0,this._currentMoviePng.width,this._currentMoviePng.height);
			this._movieSprite.graphics.endFill();
		}
		
		public function playAction(index:int):void
		{
			if(!this._actionDict.has_key(index))
				return;
			if(this._currentMoviePng.movieArg == index)
				return;
			this.startORstop(false);
			this._currentMoviePng = this._actionDict.dictionary[index];
			this.startORstop(true);
		}
		
		public function insertAction(index:int,ar:Array):void
		{
			if(this._actionDict.has_key(index))
				return;
			var png:PngMovie = new PngMovie();
			png.setPngArray(ar);
			this._actionDict.dictionary[index] = png;
		}
		
		public function removeAction(index:int):void
		{
			if(!this._actionDict.has_key(index))
				return;
			if(this._currentMoviePng && index == this._currentMoviePng.movieArg)
			{
				this.startORstop(false);
				this._currentMoviePng = null;
			}
			this._actionDict.remove(index);
		}
	}
}